<script setup lang='ts' name="object-management-add">
import { useActManageAddOrUpdate, useActManageCouponAddOrUpdate, useActManageShow } from '@fl/api/anjutong/activity-management'
import type { actManageSaveParam } from '@fl/api/anjutong/model/activity-management-model'
import type { PlusColumn } from 'plus-pro-components'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { couponDataPage, couponDetail, getBusinessBlocksList, getProjects } from '@fl/api/anjutong'
import { formatTime } from '@fl/utils'
import FlUpload from '@fl/components/fl-upload.vue'
import { useDicts } from '../hooks/use-dicts'

const { dicts: { ActType, NoticeType } } = useDicts()

const { go } = useRouter()
const route = useRoute()

const _id = route.query?.id as string
const id = ref(_id ?? '')
const isCopy = route.query.type === 'copy'
const isEdit = route.query.type === 'edit'
console.log('进来了', id.value, isCopy, isEdit)

const formRef = ref()
const businessModulesList = ref<any>([])
const projectList = ref<any>([])
const selctProject = ref<any>([])
const needCopy = ref<boolean>(true)
const couponList = ref<any>()
const couponListLoading = ref<boolean>(false)
const updateKey = ref<number>(1)

const initialState = {
    plate: '', // 业务板块
    plateName: '',
    tradeScene: '', // 优惠类型（待定）
    couponId: '', // 关联优惠券
    endTime: '',
    startTime: '',
    couponTime: [],
    superimposed: '', // 叠加情况
    activityType: '',
    activityImage: '', // 活动图片
    projectCover: 2, // 选择项目select
    projectId: [],
    amActivityProjectList: [], // 所选的项目
    // noticeType: [],
    valueAmount: undefined,
}
const state = ref<actManageSaveParam>(cloneDeep(initialState))

// 项目详情
const { data, isLoading } = useActManageShow(id)
watchEffect(() => {
    if (data.value) {
        state.value = {
            ...data.value,
            // noticeType: data.value.noticeType === 3 ? ['1', '2'] : [String(data.value.noticeType)],
            plate: [data.value.plate, data.value.plateLast],
            projectId: isCopy ? [] : data.value.amActivityProjectList.map(item => ([item.projectUnitId, item.projectId])),
            activityType: String(data.value.activityType),
            activityStatus: String(data.value.activityStatus),
            amActivityProjectList: isCopy ? [] : data.value.amActivityProjectList,
            couponTime: data.value.couponStartTime ? [data.value.couponStartTime, data.value.couponEndTime] : [],
        }
        console.log('详情', state.value)
        updateKey.value = +new Date()
    }
})

init()

function init() {
    getBusinessModules()
    getProjectList()
    getCouponList()
}

function getCouponList() {
    couponListLoading.value = true
    couponDataPage({
        couponType: 1, // 1优惠券 2折扣劵
        pageNum: 1,
        pageSize: 9999,

    }).then((res) => {
        couponList.value = res.records
        couponListLoading.value = false
    })
}

// 获取业务模块列表
function getBusinessModules() {
    getBusinessBlocksList().then((res) => {
        businessModulesList.value = res
    })
}
// 获取项目列表
function getProjectList() {
    getProjects().then((res) => {
        projectList.value = res
    })
}

function businessModulesChange(vals) {
    const currentPlate = businessModulesList.value.find(item => item.value === vals[0])
    state.value.plateName = currentPlate.label
    state.value.tradeScene = ''
    setBusinessModules(businessModulesList.value, vals)
}
// 递归获取plateName
function setBusinessModules(list, businessModules) {
    list.forEach((item) => {
        if (businessModules.includes(item.value)) {
            state.value.tradeScene += `${item.label}/`
        }
        if (item.children) {
            setBusinessModules(item.children, businessModules)
        }
    })
}

// 切换选择项目
function changeRadio() {
    console.log('changeRadio', 111)
}

function projectChange(vals) {
    // 后台要求只有动过部分项目就不传needCopy字段
    needCopy.value = false
    state.value.amActivityProjectList = []
    const values = vals.flat(Infinity)
    selctProject.value = [...new Set(values)]
    console.log('projectChange', selctProject.value)
}

// 选择关联优惠券
function couponIdChange(id: string) {
    // const target = couponList.value.find((v: any) => v.id === id)
    // console.log('优惠券', target)
    getDetailData(id)
}

// 上传图片后清除提示
function activityImageChange() {
    formRef.value.formInstance.clearValidate('activityImage')
}

// 获取详情数据
function getDetailData(id: string) {
    couponDetail({
        id,
    }).then((res) => {
        console.log('详情', res)
        state.value.amActivityProjectList = res.amCouponProjectList.reduce((pre, cur) => {
            cur.projectUnitId = cur.companyId
            cur.projectUnit = cur.companyName
            pre.push(cur)
            return pre
        }, [])
        state.value.projectId = state.value.amActivityProjectList.map(item => ([item.projectUnitId, item.projectId]))
        state.value.superimposed = String(res.superimposed)
        state.value.couponTime = [res.startTime, res.endTime]
    })
}

// 提交表单
const { isPending, mutate } = useActManageAddOrUpdate()
const { isPending: isPendingCoupon, mutate: mutateCoupon } = useActManageCouponAddOrUpdate()

async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        setProject(projectList.value, selctProject.value)
        const stateObj = toRaw(state.value)
        if (state.value.amActivityProjectList.length === 0) {
            ElMessage({
                message: '关联项目不能为空',
                type: 'warning',
            })
            return
        }
        if (new Date(state.value.endTime).getTime() < new Date(state.value.startTime).getTime()) {
            ElMessage({
                message: '开始时间不能大于截止时间',
                type: 'warning',
            })
            return
        }
        const params = {
            ...stateObj,
            endTime: formatTime(state.value.endTime, 'yyyy-MM-dd 23:59:59'),
            startTime: formatTime(state.value.startTime, 'yyyy-MM-dd 00:00:00'),
            plate: stateObj.plate[0],
            plateLast: stateObj.plate[1],
            // noticeType: stateObj.noticeType.length > 1 ? 3 : stateObj.noticeType[0],
            needCopy: isCopy && needCopy.value ? true : undefined,
            id: isEdit ? id.value : undefined,
            // valueAmount: Number(stateObj.valueAmount)
        }
        if (state.value.activityType === '2') {
            params.couponStartTime = formatTime(state.value.couponTime[0], 'yyyy-MM-dd 00:00:00')
            params.couponEndTime = formatTime(state.value.couponTime[1], 'yyyy-MM-dd 23:59:59')
            params.couponType = 1 // 优惠券
        }
        console.log('params', params)
        if (state.value.activityType === '1') {
            mutate(params, {
                onSuccess: () => {
                    formRef.value.formInstance.resetFields()
                    ElMessage.success('操作成功')
                    goBack()
                },
            })
        }
        else {
            if (isEdit) {
                params.amActivityProjectList = [] // 特殊：后端要求传[]，不影响详情回显
            }
            mutateCoupon(params, {
                onSuccess: () => {
                    formRef.value.formInstance.resetFields()
                    ElMessage.success('操作成功')
                    goBack()
                },
            })
        }
    }
}

// 递归获取所选项目列表
function setProject(list, projects) {
    // console.log('setProject', list, projects)
    list.forEach((item) => {
        if (projects.includes(item.companyId)) {
            state.value.amActivityProjectList.push({
                level: item.level,
                plate: state.value.plate[0],
                plateLast: state.value.plate[1],
                plateName: state.value.plateName,
                projectId: item.projectId,
                projectName: item.projectName,
                projectUnit: item.projectUnit,
                projectUnitId: item.projectUnitId,
            })
        }
        if (item.projectVOS) {
            setProject(item.projectVOS, projects)
        }
    })
}

function goBack() {
    go(-1)
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 9,
        },
        label: '业务板块',
        prop: 'plate',
    },
    {
        colProps: {
            span: 9,
        },
        label: '活动类型',
        prop: 'activityType',
        valueType: 'select',
        options: ActType,
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            maxlength: 20,
        },
        label: '活动名称',
        prop: 'activityName',
    },
    {
        colProps: {
            span: 9,
        },
        label: '关联优惠券',
        prop: 'couponId',
        valueType: 'select',
        hideInForm: computed(() => state.value.activityType !== '2'),
    },
    {
        colProps: {
            span: 9,
        },
        label: '活动优惠价值',
        prop: 'valueAmount',
    },
    {
        colProps: {
            span: 18,
        },
        label: '活动摘要',
        prop: 'activityDigest',
    },
    {
        colProps: {
            span: 9,
        },
        label: '活动开始时间',
        prop: 'startTime',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 9,
        },
        label: '活动截止时间',
        prop: 'endTime',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 9,
        },
        label: '叠加情况',
        prop: 'superimposed',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
            'disabled': !!isEdit,
        },
        label: '有效期',
        prop: 'couponTime',
        valueType: 'date-picker',
        hideInForm: computed(() => state.value.activityType !== '2'),
    },
    {
        colProps: {
            span: 24,
        },
        label: '活动图片',
        prop: 'activityImage',
    },
    {
        colProps: {
            span: 24,
        },
        label: '选择项目',
        prop: 'projectCover',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 200,
            showWordLimit: true,
        },
        label: '活动详情',
        prop: 'activityDetail',
        valueType: 'textarea',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 200,
            showWordLimit: true,
        },
        label: '适用范围',
        prop: 'activityRange',
        valueType: 'textarea',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 200,
            showWordLimit: true,
        },
        label: '使用方法',
        prop: 'usageMethod',
        valueType: 'textarea',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 200,
            showWordLimit: true,
        },
        label: '服务承诺',
        prop: 'servicePromise',
        valueType: 'textarea',
    },
    // {
    //     colProps: {
    //         span: 24,
    //     },
    //     label: '通知渠道',
    //     prop: 'noticeType',
    //     valueType: 'checkbox',
    //     options: NoticeType,
    //     hideInForm: computed(() => state.value.activityType === '2'),
    // },
    // {
    //     colProps: {
    //         span: 9,
    //     },
    //     fieldProps: {
    //         autosize: { maxRows: 4, minRows: 2 },
    //         maxlength: 200,
    //         showWordLimit: true,
    //     },
    //     label: '通知模板',
    //     prop: 'noticeTemplate',
    //     valueType: 'textarea',
    //     hideInForm: computed(() => state.value.activityType === '2'),
    // },
]

const rules = {
    plate: [
        {
            message: '业务板块',
            required: true,
        },
    ],
    activityType: [
        {
            message: '活动类型',
            required: true,
        },
    ],
    activityName: [
        {
            message: '活动名称',
            required: true,
        },
    ],
    valueAmount: [
        {
            message: '活动优惠价值',
            required: true,
        },
    ],
    activityDigest: [
        {
            message: '活动摘要',
            required: true,
        },
    ],
    endTime: [
        {
            message: '活动开始时间',
            required: true,
        },
    ],
    startTime: [
        {
            message: '活动截止时间',
            required: true,
        },
    ],
    superimposed: [
        {
            message: '叠加情况',
            required: true,
        },
    ],
    activityImage: [
        {
            message: '活动图片',
            required: true,
        },
    ],
    projectCover: [
        {
            message: '选择项目',
            required: true,
        },
    ],
    activityDetail: [
        {
            message: '活动详情',
            required: true,
        },
    ],
    activityRange: [
        {
            message: '适用范围',
            required: true,
        },
    ],
    usageMethod: [
        {
            message: '使用方法',
            required: true,
        },
    ],
    servicePromise: [
        {
            message: '服务承诺',
            required: true,
        },
    ],
    // noticeType: [
    //     {
    //         message: '通知渠道',
    //         required: true,
    //     },
    // ],
    // noticeTemplate: [
    //     {
    //         message: '通知模板',
    //         required: true,
    //     },
    // ],
}
</script>

<template>
    <ElCard shadow="never">
        <el-button @click="goBack">
            返回列表
        </el-button>

        <!-- 全部优惠券接口太慢，临时屏蔽： || couponListLoading -->
        <ElSkeleton v-if="isLoading"
                    :rows="5"
        />

        <template v-else>
            <div class="mt-20">
                <h3 class="title">
                    活动基础信息
                </h3>

                <PlusForm ref="formRef"
                          v-model="state"
                          :columns="columns"
                          :label-width="120"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                          label-position="top"
                >
                    <template #plus-field-plate>
                        <el-cascader v-model="state.plate"
                                     :options="businessModulesList"
                                     :disabled="isEdit"
                                     style="width: 100%"
                                     @change="businessModulesChange"
                        />
                    </template>

                    <template #plus-field-superimposed>
                        <el-select v-model="state.superimposed"
                                   clearable
                                   placeholder="请选择"
                                   :disabled="isEdit"
                        >
                            <el-option label="不可叠加"
                                       value="0"
                            />

                            <el-option label="可叠加其他类型的优惠"
                                       value="1"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-couponId>
                        <el-select v-model="state.couponId"
                                   clearable
                                   placeholder="请选择"
                                   :disabled="isEdit"
                                   @change="couponIdChange"
                        >
                            <el-option v-for="(item, index) in couponList"
                                       :key="index"
                                       :label="item.couponName"
                                       :value="item.id"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-valueAmount>
                        <el-input v-model="state.valueAmount"
                                  maxlength="10"
                        />
                    </template>

                    <template #plus-field-projectCover>
                        <!-- :disabled="isEdit" -->
                        <el-radio-group v-model="state.projectCover"
                                        style="width:100%;"
                                        @change="changeRadio"
                        >
                            <!-- <el-radio :value="1">
                                全部项目
                            </el-radio> -->
                            <el-radio :value="2">
                                部分项目
                            </el-radio>
                        </el-radio-group>

                        <el-cascader v-model="state.projectId"
                                     style="width:75%;padding-right:4px;"
                                     :props="{
                                         multiple: true,
                                         checkStrictly: true,
                                         value: 'companyId',
                                         label: 'companyName',
                                         children: 'projectVOS',
                                     }"
                                     clearable
                                     filterable
                                     :options="projectList"
                                     :disabled="state.projectCover === 1 || isEdit"
                                     @change="projectChange"
                        />
                    </template>

                    <template #plus-field-activityImage>
                        <div class="flex">
                            <FlUpload :key="String(updateKey)"
                                      v-model="state.activityImage"
                                      tips="大小5M以内"
                                      @success="activityImageChange"
                            />
                        </div>
                    </template>
                </plusform>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <SubmitBtn type="primary"
                           :loading="isPending || isPendingCoupon"
                           @click="submit"
                >
                    保存
                </SubmitBtn>

                <el-button @click="goBack">
                    取消
                </el-button>
            </div>
        </template>
    </ElCard>
</template>

<style lang="less" scoped>
.title {
    font-size: 20px;
    font-weight: 600;
    margin: 20px 0 16px 0;
}
:deep(.w-full) {
    display: flex;
    .el-upload__tip {
        height: 150px;
        line-height: 260px;
        margin-left: 10px;
    }
}
</style>
